{% load static %}
<link rel="stylesheet" href={% static "css/tree_filter.css" %}>
<link rel="stylesheet" href={% static "css/jstree-themes/default/style.css" %}>

<div class="tree-container" id="tree-container">
    <div class="tree"
         id="tree">
        <script type="application/json">
            {{ core }}
        </script>
    </div>
</div>

<script src={% static "js/jstree.min.js" %}></script>

<script>
    (function ($) {
        function pk_proto(prefix, attr_name) {
            let pre = [prefix, attr_name, ''].join('_');
            return function (id) {
                if (!id || id === '#')
                    return '#';
                return pre + id;
            }
        }

        $(document).ready(function () {
            $('.tree').each(function (idx, el) {
                let $el = $(el);
                let data_element = $el.children('script')[0];
                let data = JSON.parse(data_element.textContent || data_element.innerText);
                let treedata = data.data;
                let settings = data.settings || {};
                let core = {}
                // set treedata
                if (treedata) {
                    core.data = treedata;
                    core.themes = {
                        dots: false,
                        icons: true
                    }
                    core.animation = true
                    core.check_callback = true
                    settings.core = core
                }

                // select/deselect standard handler to update django options
                $el.on('activate_node.jstree', function (obj, e) {
                    let tree_node = e.node
                    let query_string = tree_node.data.query_string
                    let a = document.createElement('a');
                    a.setAttribute('href', query_string);
                    a.setAttribute('id', 'js_a');
                    //防止反复添加
                    if (document.getElementById('js_a')) {
                        document.body.removeChild(document.getElementById('js_a'));
                    }
                    document.body.appendChild(a);
                    a.click();

                    $('.tree').jstree('select_node', tree_node.id)

                });
                // init jstree
                $el.on('ready.jstree', function (e, data) {

                    treedata.forEach(function (tree_node) {
                        if (tree_node.state.selected === true) {
                            data.instance.open_node(tree_node.id, function () {
                            }, 1)
                        }
                    })


                })
                $el.jstree(settings);

            });


        });
    })(window._treewidget_jQuery);  // use custom jQuery object (created during jstree loading)

</script>